package map.spawnStation;

import networking.messages.syncMessages.ValueType;
import logic.common.player.Player;
import logic.common.player.playerListeners.PlayerValueListener;
import logic.ships.hunter.Hunter;
import logic.status.StatusChangedEvent;
import main.InitGame;
import main.threading.ThreadPoolController;

import com.jme.math.Vector3f;

public class SpawnPositionController implements ThreadPoolController {
		
	private SpawnPosition spawnPosition;
	private Player player;
	
	public SpawnPositionController(SpawnPosition spawnPosition, Player player) {
		assert(InitGame.get().isServer());
		this.spawnPosition = spawnPosition;
		this.player = player;
		
		player.getTeam().getIngameState().getThreadPool().registerController(this);
		
		addPlayerListener();
	}
	
	protected void addPlayerListener() {
		player.addPlayerValueListener(new PlayerValueListener() {
			@Override
			public void valueChanged(StatusChangedEvent event) {
				if(event.getType() == ValueType.Deaths) player.changeNearSpawnPosition(null);
			}
		});
	}
	
	@Override
	public void update(Float time) {
		Hunter hunter = player.getHunter();
		if(hunter == null || hunter.getParent() == null) return;
		
		Vector3f spawnStationLocation = spawnPosition.getLocalTranslation();
		
		Vector3f pilotLocation = hunter.getLocalTranslation();
		float distance = pilotLocation.distance(spawnStationLocation);
		
		if(distance <= spawnPosition.getActionRadius()) 
			player.changeNearSpawnPosition(spawnPosition);
		else if(player.getNearSpawnPosition() == spawnPosition) 
			player.changeNearSpawnPosition(null);
	}
}